/**
 * Copyright 2015-2016
 */
package com.roncoo.education.component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

/**
 * @author wei.liu
 */
@Component
public class RoncooRedisComponent {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	public void set(String key, String value) {

		ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
		if (!this.stringRedisTemplate.hasKey(key)) {
			ops.set(key, value);
			System.out.println("set key success");
		} else {
			// 存在则打印之前的value值
			System.out.println("this key = " + ops.get(key));
		}

	}

	public String get(String key) {
		return this.stringRedisTemplate.opsForValue().get(key);
	}

	public void del(String key) {
		this.stringRedisTemplate.delete(key);
	}

	public void multiSet() {
		Map m = new HashMap<>();
		m.put("liuwei", "liuwei");
		m.put("liuwei2", "liuwei2");
		
		this.stringRedisTemplate.opsForValue().multiSet(m);
	}

	/**
	 * 
	 * @Description:目前不支持集群
	 */
	public void pipeline() {
		List<Object> results = stringRedisTemplate.executePipelined(new RedisCallback<Object>() {
			public Object doInRedis(RedisConnection connection) throws DataAccessException {
				StringRedisConnection stringRedisConn = (StringRedisConnection) connection;
				for (int i = 0; i < 10; i++) {
					// stringRedisConn.rPop("myqueue");
					stringRedisConn.getSet("k" + i, "k" + i);
					try {
						System.err.println(i);
						TimeUnit.SECONDS.sleep(1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				return null;
			}
		});
	}
	public void pipeline2() {
		List<Object> results = stringRedisTemplate.executePipelined(new RedisCallback<Object>() {
			public Object doInRedis(RedisConnection connection) throws DataAccessException {
				StringRedisConnection stringRedisConn = (StringRedisConnection) connection;
				stringRedisConn.openPipeline();
				stringRedisConn.set("f", "f");
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				stringRedisConn.set("f2", "f2");
				stringRedisConn.closePipeline();
				return null;
			}
		});
	}

}
